package libs

import (
	"fmt"
	"net/url"
	"os"
	"regexp"
	"strings"
)

func MkdirByPath(path string) error {
	_, err := os.Stat(path)
	if err == nil {
		return nil
	}
	if os.IsNotExist(err) {
		err = os.MkdirAll(path, 0777)
	}
	return err
}

func MkdirByFile(file string) error {
	filelist := strings.Split(file, "/")
	s := "/" + filelist[len(filelist)-1]
	//fmt.Println(s)
	path := strings.Replace(file, s, "", 1)
	//fmt.Println(path)
	err := MkdirByPath(path)
	return err
}

func MkdirByUrl(u string) (string, error) {
	s, err := url.Parse(u)
	if err != nil {
		return "", err
	}
	filename := s.Host + s.Path
	reg := regexp.MustCompile(`(\w|\d|_)*\.[a-z]{3,5}$`)
	name := reg.FindString(filename)
	if name == "" {
		name = "/index"
	} else {
		name = "/" + name
	}
	pathname := strings.Replace(filename, name, "", -1)
	fmt.Println(pathname)
	_, err = os.Stat(pathname)
	if err == nil {
		return filename, nil
	}
	if os.IsNotExist(err) {
		err = os.MkdirAll(pathname, 0777)
		return filename, nil
	}
	return "", err
}
